package com.vast.vastlcd;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchesListener2;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.vast.vastlcd.connection.LCDPipeConnection;
import com.vast.vastlcd.connection.LCDSocketConnection;
import com.vast.vastlcd.preferences.PreferenceConstants;
import com.vast.vastlcd.views.ImageView;


public class PluginLauncher implements IStartup, ILaunchesListener2 {
	private static boolean use_socket = true;
	private static boolean is_server = true;
	private static String INTERFACE_TYPE="Socket";
	private static String SERVER_OR_CLIENT = "Server";
	private static String SOCKET_HOSTNAME="localhost";
	private static int SOCKET_PORTNUMBER = 7625;
	
	public void earlyStartup() {
		DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this);
	}
	
	public void dispose() {
		DebugPlugin.getDefault().getLaunchManager().removeLaunchListener(this);
	}

	private String strpipe;
	//private String strlabel;
	
	private String convertNamePipe(String pipeName) {
		String finalPipeName = "";
		SOCKET_HOSTNAME   = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SOCKET_HOSTNAME);
		SOCKET_PORTNUMBER = Activator.getDefault().getPreferenceStore().getInt(PreferenceConstants.P_SOCKET_PORTNUMBER); 
		SERVER_OR_CLIENT  = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SERVER_OR_CLIENT_TYPE);
		INTERFACE_TYPE    = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_INTERFACE_TYPE);
		if (SERVER_OR_CLIENT.equals("Server"))
		{
			is_server = true;
		}else {
			is_server = false;
		}
		if (INTERFACE_TYPE.equals("Socket")) {
			use_socket = true;
		} else {
			use_socket = false;
		}
		if(!use_socket) {
		// Check for windows / unix
		// Windows pipes have to be in a special place, Unix named pipes can be anywhere
		String os = System.getProperty("os.name");
		if( os.toLowerCase().contains("win")) {
			if (pipeName.startsWith("\\\\"))
				finalPipeName = pipeName; // Possible non-local user defined pipe
			else
				finalPipeName = "\\\\.\\PIPE\\" + pipeName; // Local pipe
		}				
		else 
			finalPipeName = pipeName;
		}
		else
		{
			finalPipeName = SOCKET_HOSTNAME;
		}
		
		return finalPipeName;
	}
	
	public void launchesAdded(ILaunch[] launches) {
		for (ILaunch l : launches) {
			ILaunchConfiguration lc = l.getLaunchConfiguration();
			String[] filters = 
				Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_TRIGGERS).split(";");
			try {					
					String strPCXFile = lc.getAttribute("pcxfile","");
					if (strPCXFile.equals(""))
						return;
					
					String strProject = lc.getAttribute("org.eclipse.cdt.launch.PROJECT_ATTR","");
					String filePath = "/"+strProject+"/"+strPCXFile;
						
					IWorkspace ws = ResourcesPlugin.getWorkspace();
					IFile file = ws.getRoot().getFile(new Path(filePath));
					
					if (file.exists()) {
						//Parse pcx file and get a Document instance
						Document xmlDoc = DocumentBuilderFactory.newInstance(
								).newDocumentBuilder().parse(file.getContents());
						
						//Instanciate a XPath Query engine
		                XPath xpath = XPathFactory.newInstance().newXPath();
		                
		                /* XPath Query for every "ModuleInstance" Node from the root Node
		                 * with a "Type" attribute set to VaStGpClock value 
		                 */ 
		                XPathExpression exp;
		                NodeList liste;

		                for (String str_mod : filters) {
		                
							exp = xpath.compile("//ModuleInstance[@Type='"+str_mod+"']");
			                liste = (NodeList)exp.evaluate(xmlDoc,XPathConstants.NODESET);
			                /* XPath Query for the "Value" attribute 
			                 * of every "ParameterOverride" Node from the current Node 
			                 */
							exp = xpath.compile(".//ParameterOverride[@Name='LcdPipeName']/@Value");
			                
							//Add a Terminal for each VaSTGpSocket of the pcx file
							for (int it = 0 ; it< liste.getLength();it++) {
								Element epcx = (Element)liste.item(it);
								//strlabel = epcx.getAttribute("InstanceName");
								strpipe = convertNamePipe(exp.evaluate(epcx));
								
								PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
									public void run() {
										IWorkbenchWindow win = (PlatformUI.getWorkbench().getWorkbenchWindows())[0];
										try {
											
											ImageView imv = (ImageView)win.getActivePage().showView(
												"com.vast.vastlcd.views.ImageView");
											if(!use_socket){
												imv.getConnectionManager().setConnection(new LCDPipeConnection(strpipe, false));
											} else {
												imv.getConnectionManager().setConnection(new LCDSocketConnection(strpipe, SOCKET_PORTNUMBER, is_server));
											}
											imv.getConnectionManager().startClient();
											
										} catch (PartInitException e) {
											e.printStackTrace();
										}
									}
								});		
								
								
							}	
		                }
					}
				
			} catch (Exception e) {}	
		}	
		
	}

	public void launchesChanged(ILaunch[] launches) {}

	public void launchesRemoved(ILaunch[] launches) {}

	public void launchesTerminated(ILaunch[] launches) {
		
	}

}
